package com.emm.yixun.customer.service.impl.app.manage;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.emm.yixun.basic.service.CustomerService;
import com.emm.yixun.basic.service.DataPermissionService;
import com.emm.yixun.basic.service.UserService;
import com.emm.yixun.basic.mapper.BaseCodeValueMapper;
import com.emm.yixun.common.app.GetCustomerListReqDto;
import com.emm.yixun.common.app.GetCustomerListResDto;
import com.emm.yixun.common.app.servletentity.CustomerListRes;
import com.emm.yixun.common.enums.ResultEnum;
import com.emm.yixun.common.exception.XFUNExceptionCode;
import com.emm.yixun.common.model.BaseCodeValue;
import com.emm.yixun.common.model.Customer;
import com.emm.yixun.common.model.User;
import com.emm.yixun.common.model.appDto.CustomerCountDto;
import com.emm.yixun.common.model.dto.CustomerDto;
import com.emm.yixun.common.model.dto.UserDto;
import com.emm.yixun.common.model.enums.CustomerStatusEnum;
import com.emm.yixun.common.model.enums.DelFlagEnum;
import com.emm.yixun.common.model.enums.IntentionLevelEnum;
import com.emm.yixun.common.model.enums.ProcessStatusEnum;
import com.emm.yixun.common.page.Page;
import com.emm.yixun.common.page.PageUtil;

@Service("getCustomerListManage")
public class GetCustomerListManage {

	@Autowired
	private CustomerService customerService;
	@Autowired
	private UserService userService;
	@Autowired
	private DataPermissionService dataPermissionService;
	@Autowired
	private BaseCodeValueMapper baseCodeValueMapper;
	
	/**
	 * 查询客户列表
	 * @param reqDto
	 * @return
	 */
	public GetCustomerListResDto getCustomerList(GetCustomerListReqDto reqDto) {
		GetCustomerListResDto resDto = new GetCustomerListResDto();
		CustomerDto customerDto = new CustomerDto();
		//客户数据权限校验
		String dataPermission = null;
		if("2".equals(reqDto.getType())){//逾期未签约
			dataPermission = dataPermissionService.dataPermissionCondition(Long.valueOf(reqDto.getUserId()), "menu_0100_0001", "t", null);
		}else if("3".equals(reqDto.getType())){//逾期未付款
			dataPermission = dataPermissionService.dataPermissionCondition(Long.valueOf(reqDto.getUserId()), "menu_0100_0002", "t", null);
		}else{
			dataPermission = dataPermissionService.dataPermissionCondition(Long.valueOf(reqDto.getUserId()), "menu_0006_0001", "t", null);
		}
		String [] str_permission = dataPermission.split(":");
		if("00".equals(str_permission[0])){
			resDto.setErrorCode(XFUNExceptionCode.USER_CUSTOMERNOEXIST.getCode());
			resDto.setErrorMsg(XFUNExceptionCode.USER_CUSTOMERNOEXIST.getDesin());
			resDto.setResult(ResultEnum.FAILURE.getNo());
			return resDto;
		}
		//组装查询筛选条件
		String pageNumber = reqDto.getPageNumber();
		String pageSize = reqDto.getPageSize();
		Page<Customer> customerPage = null;
//		User user = userService.selectById(Long.valueOf(reqDto.getUserId()));
		if("1".equals(reqDto.getType())){//待处理客户
			CustomerCountDto cusCountDto = new CustomerCountDto();
			cusCountDto = createQueryCondition2(cusCountDto, reqDto);
			cusCountDto.setMerchantId(String.valueOf(reqDto.getMerchantId()));
			cusCountDto.setProjectCode(reqDto.getProjectCode());
			cusCountDto.setDataPermission(str_permission[1]);
			cusCountDto.setUserId(reqDto.getUserId());
			customerPage = customerService.getCustomerCountList(cusCountDto, PageUtil.begin(Integer.parseInt(pageNumber) , Integer.parseInt(pageSize)), Integer.parseInt(pageSize));
		}else if("2".equals(reqDto.getType())){//逾期未签约
			CustomerCountDto cusCountDto = new CustomerCountDto();
			cusCountDto = createQueryCondition2(cusCountDto, reqDto);
			cusCountDto.setMerchantId(String.valueOf(reqDto.getMerchantId()));
			cusCountDto.setDataPermission(str_permission[1]);
			cusCountDto.setProjectCode(reqDto.getProjectCode());
			customerPage = customerService.getSubscribeCustomerList(cusCountDto, PageUtil.begin(Integer.parseInt(pageNumber) , Integer.parseInt(pageSize)), Integer.parseInt(pageSize));
		}else if("3".equals(reqDto.getType())){//逾期未付款
			CustomerCountDto cusCountDto = new CustomerCountDto();
			cusCountDto = createQueryCondition2(cusCountDto, reqDto);
			cusCountDto.setMerchantId(String.valueOf(reqDto.getMerchantId()));
			cusCountDto.setDataPermission(str_permission[1]);
			cusCountDto.setProjectCode(reqDto.getProjectCode());
			customerPage = customerService.getPaymentCustomerList(cusCountDto, PageUtil.begin(Integer.parseInt(pageNumber) , Integer.parseInt(pageSize)), Integer.parseInt(pageSize));
		}else if("4".equals(reqDto.getType())){//未完善客户信息
			CustomerCountDto cusCountDto = new CustomerCountDto();
			cusCountDto = createQueryCondition2(cusCountDto, reqDto);
			cusCountDto.setMerchantId(String.valueOf(reqDto.getMerchantId()));
			cusCountDto.setDataPermission(str_permission[1]);
			cusCountDto.setProjectCode(reqDto.getProjectCode());
			customerPage = customerService.getImperfectCustomerList(cusCountDto,PageUtil.begin(Integer.parseInt(pageNumber) , Integer.parseInt(pageSize)), Integer.parseInt(pageSize));
		}
		else{//客户列表
			customerDto = createQueryCondition(customerDto, reqDto);
			customerDto.setMerchantId(reqDto.getMerchantId());
			customerDto.setDataPermission(str_permission[1]);
			customerDto.setProjectCode(reqDto.getProjectCode());
			customerPage = customerService.getCustomerList(customerDto, PageUtil.begin(Integer.parseInt(pageNumber) , Integer.parseInt(pageSize)), Integer.parseInt(pageSize));
		}
		resDto.setPageNumber(pageNumber);
		resDto.setPageSize(pageSize);
		resDto.setResult("1");
		resDto.setTotalPage(String.valueOf(customerPage.getTotalPages()));
		resDto.setTotalCount(String.valueOf(customerPage.getTotal()));
		List<Customer> customerList = customerPage.getRows();
		List<CustomerListRes> customerResList = new ArrayList<CustomerListRes>();
		//格式化客户创建时间
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		for(Customer customer: customerList){
			CustomerListRes customerListRes = new CustomerListRes();
			customerListRes.setCustomerId(String.valueOf(customer.getId()));
			customerListRes.setCustomerName(customer.getCustomerName());
			customerListRes.setStar(customer.getCustomerStar());
			if(customer.getIntentionLevel() !=null && !"".equals(customer.getIntentionLevel()) && !"null".equals(customer.getIntentionLevel())){
				customerListRes.setIntentionLevel(IntentionLevelEnum.getByNo(customer.getIntentionLevel()).getDes());
			}
			if(customer.getCustomerOrigin() != null && !"".equals(customer.getCustomerOrigin()) && !"null".equals(customer.getCustomerOrigin())){
				BaseCodeValue baseCodeValue = baseCodeValueMapper.selectEntityById(Long.valueOf(customer.getCustomerOrigin()));
				if(baseCodeValue != null){
					customerListRes.setCustomerOrigin(baseCodeValue.getCodeName());
				}
			}
			//是否多套交易
			if(customer.getCustomerTradeStatus() != null && "4".equals(customer.getCustomerTradeStatus())){
				customerListRes.setIsMoreTrade("1");
			}else{
				customerListRes.setIsMoreTrade("0");
			}
			if(customer.getCustomerStatus() != null && !"".equals(customer.getCustomerStatus()) && !"null".equals(customer.getCustomerStatus())){
				customerListRes.setCustomerStatus(CustomerStatusEnum.getByNo(customer.getCustomerStatus()).getDes());
			}
			customerListRes.setCreateTime(sdf.format(customer.getCreateTime()));
			customerListRes.setMobile(customer.getCustomerPhone());
			customerListRes.setCustomerSex(customer.getCustomerSex());
			//归属人姓名
			UserDto userDto = new UserDto();
			userDto.setUserCode(customer.getUserCode());
			userDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
			User userEntity = userService.selectByDto(userDto);
			if(userEntity != null){
				customerListRes.setAttributionName(userEntity.getUserName());
			}else{
				customerListRes.setAttributionName(null);
			}

			//判断是否拥有查看权限
			customerListRes.setDataAuthority(
					dataAuthority(customer.getAccessCode(),
							customer.getUserCode(),
							customer.getSalesGroupId() == null ?null:customer.getSalesGroupId().toString(),
							str_permission[1])
			);

			customerResList.add(customerListRes);
		}
		resDto.setCustomerList(customerResList);
		return resDto;
	}

	/**
	 * 查询客户列表
	 * @param reqDto
	 * @return
	 */
	public GetCustomerListResDto getCustomerListLC(GetCustomerListReqDto reqDto) {
		GetCustomerListResDto resDto = new GetCustomerListResDto();
		CustomerDto customerDto = new CustomerDto();
		//客户数据权限校验
		String dataPermission = null;
		if("2".equals(reqDto.getType())){//逾期未签约
			dataPermission = dataPermissionService.dataPermissionCondition(Long.valueOf(reqDto.getUserId()), "menu_0100_0001", "t", null);
		}else if("3".equals(reqDto.getType())){//逾期未付款
			dataPermission = dataPermissionService.dataPermissionCondition(Long.valueOf(reqDto.getUserId()), "menu_0100_0002", "t", null);
		}else{
			dataPermission = dataPermissionService.dataPermissionCondition(Long.valueOf(reqDto.getUserId()), "menu_0006_0001", "t", null);
		}
		String [] str_permission = dataPermission.split(":");
		if("00".equals(str_permission[0])
				|| str_permission[1].indexOf("1=2") >= 0){
			resDto.setErrorCode(XFUNExceptionCode.USER_CUSTOMERNOEXIST.getCode());
			resDto.setErrorMsg(XFUNExceptionCode.USER_CUSTOMERNOEXIST.getDesin());
			resDto.setResult(ResultEnum.FAILURE.getNo());
			return resDto;
		}
		//组装查询筛选条件
		String pageNumber = reqDto.getPageNumber();
		String pageSize = reqDto.getPageSize();
		Page<Customer> customerPage = null;
//		User user = userService.selectById(Long.valueOf(reqDto.getUserId()));
		if("1".equals(reqDto.getType())){//待处理客户
			CustomerCountDto cusCountDto = new CustomerCountDto();
			cusCountDto = createQueryCondition3(cusCountDto, reqDto);
			cusCountDto.setMerchantId(String.valueOf(reqDto.getMerchantId()));
			cusCountDto.setProjectCode(reqDto.getProjectCode());
			//cusCountDto.setDataPermission(str_permission[1]);
			cusCountDto.setUserId(reqDto.getUserId());
			customerPage = customerService.getCustomerCountList(cusCountDto, PageUtil.begin(Integer.parseInt(pageNumber) , Integer.parseInt(pageSize)), Integer.parseInt(pageSize));
		}else if("2".equals(reqDto.getType())){//逾期未签约
			CustomerCountDto cusCountDto = new CustomerCountDto();
			cusCountDto = createQueryCondition3(cusCountDto, reqDto);
			cusCountDto.setMerchantId(String.valueOf(reqDto.getMerchantId()));
			//cusCountDto.setDataPermission(str_permission[1]);
			cusCountDto.setProjectCode(reqDto.getProjectCode());
			customerPage = customerService.getSubscribeCustomerList(cusCountDto, PageUtil.begin(Integer.parseInt(pageNumber) , Integer.parseInt(pageSize)), Integer.parseInt(pageSize));
		}else if("3".equals(reqDto.getType())){//逾期未付款
			CustomerCountDto cusCountDto = new CustomerCountDto();
			cusCountDto = createQueryCondition3(cusCountDto, reqDto);
			cusCountDto.setMerchantId(String.valueOf(reqDto.getMerchantId()));
			//cusCountDto.setDataPermission(str_permission[1]);
			cusCountDto.setProjectCode(reqDto.getProjectCode());
			customerPage = customerService.getPaymentCustomerList(cusCountDto, PageUtil.begin(Integer.parseInt(pageNumber) , Integer.parseInt(pageSize)), Integer.parseInt(pageSize));
		}else if("4".equals(reqDto.getType())){//未完善客户信息
			CustomerCountDto cusCountDto = new CustomerCountDto();
			cusCountDto = createQueryCondition3(cusCountDto, reqDto);
			cusCountDto.setMerchantId(String.valueOf(reqDto.getMerchantId()));
			//cusCountDto.setDataPermission(str_permission[1]);
			cusCountDto.setProjectCode(reqDto.getProjectCode());
			customerPage = customerService.getImperfectCustomerList(cusCountDto,PageUtil.begin(Integer.parseInt(pageNumber) , Integer.parseInt(pageSize)), Integer.parseInt(pageSize));
		}
		else{//客户列表
			customerDto = createQueryConditionLC(customerDto, reqDto);
			customerDto.setMerchantId(reqDto.getMerchantId());
			//customerDto.setDataPermission(str_permission[1]);
			customerDto.setProjectCode(reqDto.getProjectCode());
			customerPage = customerService.getCustomerList(customerDto, PageUtil.begin(Integer.parseInt(pageNumber) , Integer.parseInt(pageSize)), Integer.parseInt(pageSize));
		}
		resDto.setPageNumber(pageNumber);
		resDto.setPageSize(pageSize);
		resDto.setResult("1");
		resDto.setTotalPage(String.valueOf(customerPage.getTotalPages()));
		resDto.setTotalCount(String.valueOf(customerPage.getTotal()));
		List<Customer> customerList = customerPage.getRows();
		List<CustomerListRes> customerResList = new ArrayList<CustomerListRes>();
		//格式化客户创建时间
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		for(Customer customer: customerList){
			CustomerListRes customerListRes = new CustomerListRes();
			customerListRes.setCustomerId(String.valueOf(customer.getId()));
			customerListRes.setCustomerName(customer.getCustomerName());
			customerListRes.setStar(customer.getCustomerStar());
			if(customer.getIntentionLevel() !=null && !"".equals(customer.getIntentionLevel()) && !"null".equals(customer.getIntentionLevel())){
				customerListRes.setIntentionLevel(IntentionLevelEnum.getByNo(customer.getIntentionLevel()).getDes());
			}
			if(customer.getCustomerOrigin() != null && !"".equals(customer.getCustomerOrigin()) && !"null".equals(customer.getCustomerOrigin())){
				BaseCodeValue baseCodeValue = baseCodeValueMapper.selectEntityById(Long.valueOf(customer.getCustomerOrigin()));
				if(baseCodeValue != null){
					customerListRes.setCustomerOrigin(baseCodeValue.getCodeName());
				}
			}
			//是否多套交易
			if(customer.getCustomerTradeStatus() != null && "4".equals(customer.getCustomerTradeStatus())){
				customerListRes.setIsMoreTrade("1");
			}else{
				customerListRes.setIsMoreTrade("0");
			}
			if(customer.getCustomerStatus() != null && !"".equals(customer.getCustomerStatus()) && !"null".equals(customer.getCustomerStatus())){
				customerListRes.setCustomerStatus(CustomerStatusEnum.getByNo(customer.getCustomerStatus()).getDes());
			}
			customerListRes.setCreateTime(sdf.format(customer.getCreateTime()));
			customerListRes.setMobile(customer.getCustomerPhone());
			customerListRes.setCustomerSex(customer.getCustomerSex());
			//归属人姓名
			UserDto userDto = new UserDto();
			userDto.setUserCode(customer.getUserCode());
			userDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
			User userEntity = userService.selectByDto(userDto);
			if(userEntity != null){
				customerListRes.setAttributionName(userEntity.getUserName());
			}else{
				customerListRes.setAttributionName(null);
			}
			//判断是否拥有查看权限
			customerListRes.setDataAuthority(
					dataAuthority(customer.getAccessCode(), 
							customer.getUserCode(), 
							customer.getSalesGroupId() == null ?null:customer.getSalesGroupId().toString(),
							str_permission[1])
			);
			customerResList.add(customerListRes);
		}
		resDto.setCustomerList(customerResList);
		return resDto;
	}
	
	/**
	 * 判断是否拥有查看权限 （0 无权限 1有权限）
	 * @return
	 */
	public String dataAuthority(String accessCode, String userCode, 
			String salesGroupId, String permission) {
		if(StringUtils.isNotBlank(accessCode)) {
			accessCode = "access_code = '" + accessCode;
		}
		if(StringUtils.isNotBlank(userCode)) {
			userCode = "user_code = '" + userCode;
		}
		if(StringUtils.isNotBlank(salesGroupId)) {
			salesGroupId = "sales_group_id = " + salesGroupId;
		}
		//当权限为管理员时
		if(permission.indexOf("1=1") >= 0) {
			return "1";
		}
		//当权限为个人权限时
		if(StringUtils.isNotBlank(userCode) 
				&& permission.indexOf("user_code") >=0) {
			if(permission.indexOf(userCode) >= 0) {
				return "1";
			}
			//个人权限不匹配时，返回无权限
			return "0";
		}
		//当权限为项目组时
		if(StringUtils.isNotBlank(accessCode) 
				&& permission.indexOf(accessCode) >= 0) {
			return "1";
		}
		//当权限为销售组时
		if(StringUtils.isNotBlank(salesGroupId) 
				&& permission.indexOf(salesGroupId) >= 0) {
			return "1";
		}
		return "0";
	}
	
	/**
	 * 
	 * @param customerDto 查询Dto
	 * @param sort 排序：1、最新创建；2、最新更新(默认)；3、最新跟进；4、按标星
	 * @param type 1、待处理客户；2、逾期未签约；3、逾期未付款
	 * @param screenType 1、客户状态；2、意向等级；3、跟进时间；4、首次接触方式；5、归属人
	 * @param screenValue
	 * screenType等于1时：1 来电、2 问询、3 认筹（无房）、4 小定、5  认购、6 签约、 7 无意向
	 * screenType等于2时：1 A+、2 A、3 B、4 C、5 D；
	 * screenType等于3时：1、3天未跟进；2、一周未跟进；3、两周未跟进；4、一月未跟进；5、两月未跟进；
	 * screenType等于4时：1 来电、2 来访、 3 其他
	 * screenType等于5时：归属人Id（即为客户所属经纪人Id）
	 * @return customerDto
	 */
	public CustomerDto createQueryCondition(CustomerDto customerDto, GetCustomerListReqDto reqDto){
		String type = reqDto.getType();
		String sort = reqDto.getSort();
		String screenType = reqDto.getScreenType();
		String screenValue = reqDto.getScreenValue();
		//需进行过滤的客户ID
		Set<String> customerIdSet = new HashSet<String>();
		//以上述查出来会员ID进行条件组装
		String customerCondition = "";
		if("1".equals(type)){
			//待处理客户
			customerDto.setProcessStatus(ProcessStatusEnum.NO.getNo());//处理状态:[{key:process_status,values:[{no:0,alias:NO,remark:未处理},{no:1,alias:YES,remark:已处理}]}]
		}
		if("1".equals(screenType)){
			//客户状态customer_status: 1 来电、2 问询、3 认筹（无房）、4 小定、5  认购、6 签约、 7 无意向

			//2016-10-13修改,枚举值变更
			//客户状态customer_status: 1 问询、2 来访、3 认筹、4 认购、5  签约、6 无意向
			switch (screenValue) {
			case "1":
				customerDto.setCustomerStatus(CustomerStatusEnum.TELEPHONE.getNo());
				break;
			case "2":
				customerDto.setCustomerStatus(CustomerStatusEnum.VISIT.getNo());
				break;
			case "3":
				customerDto.setCustomerStatus(CustomerStatusEnum.RENCHOU.getNo());
				break;
			case "4":
				customerDto.setCustomerStatus(CustomerStatusEnum.RENGOU.getNo());
				break;
			case "5":
				customerDto.setCustomerStatus(CustomerStatusEnum.QIANYUE.getNo());
				break;
			case "6":
				customerDto.setCustomerStatus(CustomerStatusEnum.DUOTAO.getNo());
				break;
			default:
				break;
			}
		}else if("2".equals(screenType)){
			//意向等级: 1 A+、2 A、3 B、4 C、5 D
			//intention_level
			switch (screenValue) {
			case "1":
				customerDto.setIntentionLevel(IntentionLevelEnum.A_PLUS.getNo());
				break;
			case "2":
				customerDto.setIntentionLevel(IntentionLevelEnum.A.getNo());
				break;
			case "3":
				customerDto.setIntentionLevel(IntentionLevelEnum.B.getNo());
				break;
			case "4":
				customerDto.setIntentionLevel(IntentionLevelEnum.C.getNo());
				break;
			case "5":
				customerDto.setIntentionLevel(IntentionLevelEnum.D.getNo());
				break;
			default:
				break;
			}
		}else if("3".equals(screenType)){
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			//跟进情况: 1、3天未跟进；2、一周未跟进；3、两周未跟进；4、一月未跟进；5、两月未跟进；
			//根据最后跟进时间进行比较 last_follow_time,如自己本人新建客户并未分配则根据客户创建时间来查询
			Calendar calendar = Calendar.getInstance();
			try {
				switch (screenValue) {
				case "1":
					calendar.add(Calendar.DAY_OF_MONTH, -3);
					customerDto.setLastFollowTimeBefore(sdf.parse(formatDate(calendar)));
					customerDto.setLastFollowTimeAfter(sdf.parse(formatDate(Calendar.getInstance())));
					break;
				case "2":
					calendar.add(Calendar.DAY_OF_MONTH, -7);
					customerDto.setLastFollowTimeBefore(sdf.parse(formatDate(calendar)));
					customerDto.setLastFollowTimeAfter(sdf.parse(formatDate(Calendar.getInstance())));
					break;
				case "3":
					calendar.add(Calendar.DAY_OF_MONTH, -14);
					customerDto.setLastFollowTimeBefore(sdf.parse(formatDate(calendar)));
					customerDto.setLastFollowTimeAfter(sdf.parse(formatDate(Calendar.getInstance())));
					break;
				case "4":
					calendar.add(Calendar.DAY_OF_MONTH, -30);
					customerDto.setLastFollowTimeBefore(sdf.parse(formatDate(calendar)));
					customerDto.setLastFollowTimeAfter(sdf.parse(formatDate(Calendar.getInstance())));
					break;
				case "5":
					calendar.add(Calendar.DAY_OF_MONTH, -60);
					customerDto.setLastFollowTimeBefore(sdf.parse(formatDate(calendar)));
					customerDto.setLastFollowTimeAfter(sdf.parse(formatDate(Calendar.getInstance())));
					break;
				default:
					break;
				}
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}else if("4".equals(screenType)){
			//首次接触方式: 来电、2 来访、 3 其他
			//ft_contact_way
/*			switch (screenValue) {
			case "1":
				customerDto.setFtContactWay(FtContactWayEnum.TELEPHONE.getNo());
				break;
			case "2":
				customerDto.setFtContactWay(FtContactWayEnum.VISITING.getNo());
				break;
			case "3":
				customerDto.setFtContactWay(FtContactWayEnum.OTHER.getNo());
				break;
			default:
				break;
			}*/
			if(screenValue != null && !"0".equals(screenValue)){
				customerDto.setFtContactWay(screenValue);
			}
		}else if("5".equals(screenType)){
			if(StringUtils.isNotEmpty(screenValue)){
				User userT = userService.selectById(Long.valueOf(screenValue));
				if(null != userT){
					customerDto.setUserCode(userT.getUserCode());
				}
			}
		}
		//sort 排序：1、最新创建；2、最新更新(默认)；3、最新跟进；4、按标星
		if("1".equals(sort)){
			customerDto.setOrders(" t.create_time desc ");
		}else if("2".equals(sort)){
			customerDto.setOrders(" t.update_time desc ");
		}else if("3".equals(sort)){
			customerDto.setOrders(" t.last_follow_time desc ");
		}else if("4".equals(sort)){
			customerDto.setOrders(" t.customer_star desc ");
		}else if("5".equals(sort)) {
			customerDto.setOrders(" t.intention_level, t.create_time desc ");
		}

		//组装会员过滤条件
		for (String customerId : customerIdSet) {
			if(StringUtils.isNotEmpty(customerCondition)){
				customerCondition += " or ";
			}
			customerCondition += "id = " + customerId;
		}
		customerDto.setCustomerCondition(customerCondition.equals("")?null:customerCondition);

		return customerDto;
	}
	
	/**
	 * 
	 * @param customerDto 查询Dto
	 * @param sort 排序：1、最新创建；2、最新更新(默认)；3、最新跟进；4、按标星
	 * @param type 1、待处理客户；2、逾期未签约；3、逾期未付款
	 * @param screenType 1、客户状态；2、意向等级；3、跟进时间；4、首次接触方式；5、归属人
	 * @param screenValue
	 * screenType等于1时：1 来电、2 问询、3 认筹（无房）、4 小定、5  认购、6 签约、 7 无意向
	 * screenType等于2时：1 A+、2 A、3 B、4 C、5 D；
	 * screenType等于3时：1、3天未跟进；2、一周未跟进；3、两周未跟进；4、一月未跟进；5、两月未跟进；
	 * screenType等于4时：1 来电、2 来访、 3 其他
	 * screenType等于5时：归属人Id（即为客户所属经纪人Id）
	 * @return customerDto
	 */
	public CustomerCountDto createQueryCondition2(CustomerCountDto cusCountDto, GetCustomerListReqDto reqDto){
		String type = reqDto.getType();
		String sort = reqDto.getSort();
		String screenType = reqDto.getScreenType();
		String screenValue = reqDto.getScreenValue();
		//需进行过滤的客户ID
		Set<String> customerIdSet = new HashSet<String>();
		//以上述查出来会员ID进行条件组装
		String customerCondition = "";
		if("1".equals(type)){
			//待处理客户
			cusCountDto.setProcessStatus(ProcessStatusEnum.NO.getNo());//处理状态:[{key:process_status,values:[{no:0,alias:NO,remark:未处理},{no:1,alias:YES,remark:已处理}]}]
		}
		if("1".equals(screenType)){
			//客户状态customer_status: 1 来电、2 问询、3 认筹（无房）、4 小定、5  认购、6 签约、 7 无意向
			
			//2016-10-13修改,枚举值变更
			//客户状态customer_status: 1 问询、2 来访、3 认筹、4 认购、5  签约、6 无意向
			switch (screenValue) {
			case "1":
				cusCountDto.setCustomerStatus(CustomerStatusEnum.TELEPHONE.getNo());
				break;
			case "2":
				cusCountDto.setCustomerStatus(CustomerStatusEnum.VISIT.getNo());
				break;
			case "3":
				cusCountDto.setCustomerStatus(CustomerStatusEnum.RENCHOU.getNo());
				break;
			case "4":
				cusCountDto.setCustomerStatus(CustomerStatusEnum.RENGOU.getNo());
				break;
			case "5":
				cusCountDto.setCustomerStatus(CustomerStatusEnum.QIANYUE.getNo());
				break;
			case "6":
				cusCountDto.setCustomerStatus(CustomerStatusEnum.DUOTAO.getNo());
				break;
			default:
				break;
			}
		}else if("2".equals(screenType)){
			//意向等级: 1 A+、2 A、3 B、4 C、5 D
			//intention_level
			switch (screenValue) {
			case "1":
				cusCountDto.setIntentionLevel(IntentionLevelEnum.A_PLUS.getNo());
				break;
			case "2":
				cusCountDto.setIntentionLevel(IntentionLevelEnum.A.getNo());
				break;
			case "3":
				cusCountDto.setIntentionLevel(IntentionLevelEnum.B.getNo());
				break;
			case "4":
				cusCountDto.setIntentionLevel(IntentionLevelEnum.C.getNo());
				break;
			case "5":
				cusCountDto.setIntentionLevel(IntentionLevelEnum.D.getNo());
				break;
			default:
				break;
			}
		}else if("3".equals(screenType)){
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			//跟进情况: 1、3天未跟进；2、一周未跟进；3、两周未跟进；4、一月未跟进；5、两月未跟进；
			//根据最后跟进时间进行比较 last_follow_time,如自己本人新建客户并未分配则根据客户创建时间来查询
			Calendar calendar = Calendar.getInstance();
			try {
				switch (screenValue) {
				case "1":
					calendar.add(Calendar.DAY_OF_MONTH, -3);
					cusCountDto.setLastFollowTimeBefore(sdf.parse(formatDate(calendar)));
					cusCountDto.setLastFollowTimeAfter(sdf.parse(formatDate(Calendar.getInstance())));
					break;
				case "2":
					calendar.add(Calendar.DAY_OF_MONTH, -7);
					cusCountDto.setLastFollowTimeBefore(sdf.parse(formatDate(calendar)));
					cusCountDto.setLastFollowTimeAfter(sdf.parse(formatDate(Calendar.getInstance())));
					break;
				case "3":
					calendar.add(Calendar.DAY_OF_MONTH, -14);
					cusCountDto.setLastFollowTimeBefore(sdf.parse(formatDate(calendar)));
					cusCountDto.setLastFollowTimeAfter(sdf.parse(formatDate(Calendar.getInstance())));
					break;
				case "4":
					calendar.add(Calendar.DAY_OF_MONTH, -30);
					cusCountDto.setLastFollowTimeBefore(sdf.parse(formatDate(calendar)));
					cusCountDto.setLastFollowTimeAfter(sdf.parse(formatDate(Calendar.getInstance())));
					break;
				case "5":
					calendar.add(Calendar.DAY_OF_MONTH, -60);
					cusCountDto.setLastFollowTimeBefore(sdf.parse(formatDate(calendar)));
					cusCountDto.setLastFollowTimeAfter(sdf.parse(formatDate(Calendar.getInstance())));
					break;
				default:
					break;
				}
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}else if("4".equals(screenType)){
			//首次接触方式: 来电、2 来访、 3 其他
			//ft_contact_way
			/*switch (screenValue) {
			case "1":
				cusCountDto.setFtContactWay(FtContactWayEnum.TELEPHONE.getNo());
				break;
			case "2":
				cusCountDto.setFtContactWay(FtContactWayEnum.VISITING.getNo());
				break;
			case "3":
				cusCountDto.setFtContactWay(FtContactWayEnum.OTHER.getNo());
				break;
			default:
				break;
			}*/
			if(screenValue != null && !"0".equals(screenValue)){
				cusCountDto.setFtContactWay(screenValue);
			}
		}else if("5".equals(screenType)){
			if(StringUtils.isNotEmpty(screenValue)){
				User userT = userService.selectById(Long.valueOf(screenValue));
				if(null != userT){
					cusCountDto.setUserCode(userT.getUserCode());
				}
			}
		}
		//sort 排序：1、最新创建；2、最新更新(默认)；3、最新跟进；4、按标星；5、按意向等级
		if("1".equals(sort)){
			cusCountDto.setCusSort(" t.create_time desc ");
		}else if("2".equals(sort)){
			cusCountDto.setCusSort(" t.update_time desc ");
		}else if("3".equals(sort)){
			cusCountDto.setCusSort(" t.last_follow_time desc ");
		}else if("4".equals(sort)){
			cusCountDto.setCusSort(" t.customer_star desc ");
		}else if("5".equals(sort)) {
			cusCountDto.setCusSort(" t.intention_level, t.create_time desc ");
		}
		
		//组装会员过滤条件
		for (String customerId : customerIdSet) {
			if(StringUtils.isNotEmpty(customerCondition)){
				customerCondition += " or ";
			}
			customerCondition += "id = " + customerId;
		}
		//cusCountDto.setCustomerCondition(customerCondition.equals("")?null:customerCondition);
		
		return cusCountDto;
	}

	/**
	 *
	 * @param customerDto 查询Dto
	 * @param sort 排序：1、最新创建；2、最新更新(默认)；3、最新跟进；4、按标星
	 * @param type 1、待处理客户；2、逾期未签约；3、逾期未付款
	 * @param screenType 1、客户状态；2、意向等级；3、跟进时间；4、首次接触方式；5、归属人
	 * @param screenValue
	 * screenType等于1时：1 来电、2 问询、3 认筹（无房）、4 小定、5  认购、6 签约、 7 无意向
	 * screenType等于2时：1 A+、2 A、3 B、4 C、5 D；
	 * screenType等于3时：1、3天未跟进；2、一周未跟进；3、两周未跟进；4、一月未跟进；5、两月未跟进；
	 * screenType等于4时：1 来电、2 来访、 3 其他
	 * screenType等于5时：归属人Id（即为客户所属经纪人Id）
	 * @return customerDto
	 */
	public CustomerCountDto createQueryCondition3(CustomerCountDto cusCountDto, GetCustomerListReqDto reqDto){
		String type = reqDto.getType();
		String sort = reqDto.getSort();
		String screenType = reqDto.getScreenType();
		String screenValue = reqDto.getScreenValue();
		//需进行过滤的客户ID
		Set<String> customerIdSet = new HashSet<String>();
		//以上述查出来会员ID进行条件组装
		String customerCondition = "";
		if("1".equals(type)){
			//待处理客户
			cusCountDto.setProcessStatus(ProcessStatusEnum.NO.getNo());//处理状态:[{key:process_status,values:[{no:0,alias:NO,remark:未处理},{no:1,alias:YES,remark:已处理}]}]
		}
		if("1".equals(screenType)){
			//客户状态customer_status: 1 来电、2 问询、3 认筹（无房）、4 小定、5  认购、6 签约、 7 无意向

			//2016-10-13修改,枚举值变更
			//客户状态customer_status: 1 问询、2 来访、3 认筹、4 认购、5  签约、6 无意向
			switch (screenValue) {
				case "1":
					cusCountDto.setCustomerStatus(CustomerStatusEnum.TELEPHONE.getNo());
					break;
				case "2":
					cusCountDto.setCustomerStatus(CustomerStatusEnum.VISIT.getNo());
					break;
				case "3":
					cusCountDto.setCustomerStatus(CustomerStatusEnum.RENCHOU.getNo());
					break;
				case "4":
					cusCountDto.setCustomerStatus(CustomerStatusEnum.RENGOU.getNo());
					break;
				case "5":
					cusCountDto.setCustomerStatus(CustomerStatusEnum.QIANYUE.getNo());
					break;
				case "6":
					cusCountDto.setCustomerStatus(CustomerStatusEnum.DUOTAO.getNo());
					break;
				default:
					break;
			}
		}else if("2".equals(screenType)){
			//意向等级: 1 A+、2 A、3 B、4 C、5 D
			//intention_level
			switch (screenValue) {
				case "1":
					cusCountDto.setIntentionLevel(IntentionLevelEnum.A_PLUS.getNo());
					break;
				case "2":
					cusCountDto.setIntentionLevel(IntentionLevelEnum.A.getNo());
					break;
				case "3":
					cusCountDto.setIntentionLevel(IntentionLevelEnum.B.getNo());
					break;
				case "4":
					cusCountDto.setIntentionLevel(IntentionLevelEnum.C.getNo());
					break;
				case "5":
					cusCountDto.setIntentionLevel(IntentionLevelEnum.D.getNo());
					break;
				default:
					break;
			}
		}else if("3".equals(screenType)){
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			//跟进情况: 1、3天未跟进；2、一周未跟进；3、两周未跟进；4、一月未跟进；5、两月未跟进；
			//根据最后跟进时间进行比较 last_follow_time,如自己本人新建客户并未分配则根据客户创建时间来查询
			Calendar calendar = Calendar.getInstance();
			try {
				switch (screenValue) {
					case "1":
						calendar.add(Calendar.DAY_OF_MONTH, -3);
						cusCountDto.setLastFollowTimeBefore(sdf.parse(formatDate(calendar)));
						cusCountDto.setLastFollowTimeAfter(sdf.parse(formatDate(Calendar.getInstance())));
						break;
					case "2":
						calendar.add(Calendar.DAY_OF_MONTH, -7);
						cusCountDto.setLastFollowTimeBefore(sdf.parse(formatDate(calendar)));
						cusCountDto.setLastFollowTimeAfter(sdf.parse(formatDate(Calendar.getInstance())));
						break;
					case "3":
						calendar.add(Calendar.DAY_OF_MONTH, -14);
						cusCountDto.setLastFollowTimeBefore(sdf.parse(formatDate(calendar)));
						cusCountDto.setLastFollowTimeAfter(sdf.parse(formatDate(Calendar.getInstance())));
						break;
					case "4":
						calendar.add(Calendar.DAY_OF_MONTH, -30);
						cusCountDto.setLastFollowTimeBefore(sdf.parse(formatDate(calendar)));
						cusCountDto.setLastFollowTimeAfter(sdf.parse(formatDate(Calendar.getInstance())));
						break;
					case "5":
						calendar.add(Calendar.DAY_OF_MONTH, -60);
						cusCountDto.setLastFollowTimeBefore(sdf.parse(formatDate(calendar)));
						cusCountDto.setLastFollowTimeAfter(sdf.parse(formatDate(Calendar.getInstance())));
						break;
					default:
						break;
				}
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}else if("4".equals(screenType)){
			//首次接触方式: 来电、2 来访、 3 其他
			//ft_contact_way
			/*switch (screenValue) {
			case "1":
				cusCountDto.setFtContactWay(FtContactWayEnum.TELEPHONE.getNo());
				break;
			case "2":
				cusCountDto.setFtContactWay(FtContactWayEnum.VISITING.getNo());
				break;
			case "3":
				cusCountDto.setFtContactWay(FtContactWayEnum.OTHER.getNo());
				break;
			default:
				break;
			}*/
			if(screenValue != null && !"0".equals(screenValue)){
				cusCountDto.setFtContactWay(screenValue);
			}
		}else if("5".equals(screenType)){
			if(StringUtils.isNotEmpty(screenValue)){
				User userT = userService.selectById(Long.valueOf(screenValue));
				if(null != userT){
					cusCountDto.setUserCode(userT.getUserCode());
				}
			}
		}
		//sort 排序：1、最新创建；2、最新更新(默认)；3、最新跟进；4、按标星；5、按意向等级
		if("1".equals(sort)){
			cusCountDto.setCusSort(" t.create_time desc ");
		}else if("2".equals(sort)){
			cusCountDto.setCusSort(" t.update_time desc ");
		}else if("3".equals(sort)){
			cusCountDto.setCusSort(" t.last_follow_time asc ");
		}else if("4".equals(sort)){
			cusCountDto.setCusSort(" t.customer_star desc ");
		}else if("5".equals(sort)) {
			cusCountDto.setCusSort(" t.intention_level, t.create_time desc ");
		}

		//组装会员过滤条件
		for (String customerId : customerIdSet) {
			if(StringUtils.isNotEmpty(customerCondition)){
				customerCondition += " or ";
			}
			customerCondition += "id = " + customerId;
		}
		//cusCountDto.setCustomerCondition(customerCondition.equals("")?null:customerCondition);

		return cusCountDto;
	}

	/**
	 *
	 * @param customerDto 查询Dto
	 * @param sort 排序：1、最新创建；2、最新更新(默认)；3、最新跟进；4、按标星
	 * @param type 1、待处理客户；2、逾期未签约；3、逾期未付款
	 * @param screenType 1、客户状态；2、意向等级；3、跟进时间；4、首次接触方式；5、归属人
	 * @param screenValue
	 * screenType等于1时：1 来电、2 问询、3 认筹（无房）、4 小定、5  认购、6 签约、 7 无意向
	 * screenType等于2时：1 A+、2 A、3 B、4 C、5 D；
	 * screenType等于3时：1、3天未跟进；2、一周未跟进；3、两周未跟进；4、一月未跟进；5、两月未跟进；
	 * screenType等于4时：1 来电、2 来访、 3 其他
	 * screenType等于5时：归属人Id（即为客户所属经纪人Id）
	 * @return customerDto
	 */
	public CustomerDto createQueryConditionLC(CustomerDto customerDto, GetCustomerListReqDto reqDto){
		String type = reqDto.getType();
		String sort = reqDto.getSort();
		String screenType = reqDto.getScreenType();
		String screenValue = reqDto.getScreenValue();
		//需进行过滤的客户ID
		Set<String> customerIdSet = new HashSet<String>();
		//以上述查出来会员ID进行条件组装
		String customerCondition = "";
		if("1".equals(type)){
			//待处理客户
			customerDto.setProcessStatus(ProcessStatusEnum.NO.getNo());//处理状态:[{key:process_status,values:[{no:0,alias:NO,remark:未处理},{no:1,alias:YES,remark:已处理}]}]
		}
		if("1".equals(screenType)){
			//客户状态customer_status: 1 来电、2 问询、3 认筹（无房）、4 小定、5  认购、6 签约、 7 无意向

			//2016-10-13修改,枚举值变更
			//客户状态customer_status: 1 问询、2 来访、3 认筹、4 认购、5  签约、6 无意向
			switch (screenValue) {
				case "1":
					customerDto.setCustomerStatus(CustomerStatusEnum.TELEPHONE.getNo());
					break;
				case "2":
					customerDto.setCustomerStatus(CustomerStatusEnum.VISIT.getNo());
					break;
				case "3":
					customerDto.setCustomerStatus(CustomerStatusEnum.RENCHOU.getNo());
					break;
				case "4":
					customerDto.setCustomerStatus(CustomerStatusEnum.RENGOU.getNo());
					break;
				case "5":
					customerDto.setCustomerStatus(CustomerStatusEnum.QIANYUE.getNo());
					break;
				case "6":
					customerDto.setCustomerStatus(CustomerStatusEnum.DUOTAO.getNo());
					break;
				default:
					break;
			}
		}else if("2".equals(screenType)){
			//意向等级: 1 A+、2 A、3 B、4 C、5 D
			//intention_level
			switch (screenValue) {
				case "1":
					customerDto.setIntentionLevel(IntentionLevelEnum.A_PLUS.getNo());
					break;
				case "2":
					customerDto.setIntentionLevel(IntentionLevelEnum.A.getNo());
					break;
				case "3":
					customerDto.setIntentionLevel(IntentionLevelEnum.B.getNo());
					break;
				case "4":
					customerDto.setIntentionLevel(IntentionLevelEnum.C.getNo());
					break;
				case "5":
					customerDto.setIntentionLevel(IntentionLevelEnum.D.getNo());
					break;
				default:
					break;
			}
		}else if("3".equals(screenType)){
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			//跟进情况: 1、3天未跟进；2、一周未跟进；3、两周未跟进；4、一月未跟进；5、两月未跟进；
			//根据最后跟进时间进行比较 last_follow_time,如自己本人新建客户并未分配则根据客户创建时间来查询
			Calendar calendar = Calendar.getInstance();
			try {
				switch (screenValue) {
					case "1":
						calendar.add(Calendar.DAY_OF_MONTH, -3);
						customerDto.setLastFollowTimeBefore(sdf.parse(formatDate(calendar)));
						customerDto.setLastFollowTimeAfter(sdf.parse(formatDate(Calendar.getInstance())));
						break;
					case "2":
						calendar.add(Calendar.DAY_OF_MONTH, -7);
						customerDto.setLastFollowTimeBefore(sdf.parse(formatDate(calendar)));
						customerDto.setLastFollowTimeAfter(sdf.parse(formatDate(Calendar.getInstance())));
						break;
					case "3":
						calendar.add(Calendar.DAY_OF_MONTH, -14);
						customerDto.setLastFollowTimeBefore(sdf.parse(formatDate(calendar)));
						customerDto.setLastFollowTimeAfter(sdf.parse(formatDate(Calendar.getInstance())));
						break;
					case "4":
						calendar.add(Calendar.DAY_OF_MONTH, -30);
						customerDto.setLastFollowTimeBefore(sdf.parse(formatDate(calendar)));
						customerDto.setLastFollowTimeAfter(sdf.parse(formatDate(Calendar.getInstance())));
						break;
					case "5":
						calendar.add(Calendar.DAY_OF_MONTH, -60);
						customerDto.setLastFollowTimeBefore(sdf.parse(formatDate(calendar)));
						customerDto.setLastFollowTimeAfter(sdf.parse(formatDate(Calendar.getInstance())));
						break;
					default:
						break;
				}
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}else if("4".equals(screenType)){
			//首次接触方式: 来电、2 来访、 3 其他
			//ft_contact_way
/*			switch (screenValue) {
			case "1":
				customerDto.setFtContactWay(FtContactWayEnum.TELEPHONE.getNo());
				break;
			case "2":
				customerDto.setFtContactWay(FtContactWayEnum.VISITING.getNo());
				break;
			case "3":
				customerDto.setFtContactWay(FtContactWayEnum.OTHER.getNo());
				break;
			default:
				break;
			}*/
			if(screenValue != null && !"0".equals(screenValue)){
				customerDto.setFtContactWay(screenValue);
			}
		}else if("5".equals(screenType)){
			if(StringUtils.isNotEmpty(screenValue)){
				User userT = userService.selectById(Long.valueOf(screenValue));
				if(null != userT){
					customerDto.setUserCode(userT.getUserCode());
				}
			}
		}
		//sort 排序：1、最新创建；2、最新更新(默认)；3、最新跟进；4、按标星；5、按意向等级
		if("1".equals(sort)){
			customerDto.setOrders(" t.create_time desc ");
		}else if("2".equals(sort)){
			customerDto.setOrders(" t.update_time desc ");
		}else if("3".equals(sort)){
			customerDto.setOrders(" t.last_follow_time asc ");
		}else if("4".equals(sort)){
			customerDto.setOrders(" t.customer_star desc ");
		}else if("5".equals(sort)) {
			customerDto.setOrders(" t.intention_level, t.create_time desc ");
		}

		//组装会员过滤条件
		for (String customerId : customerIdSet) {
			if(StringUtils.isNotEmpty(customerCondition)){
				customerCondition += " or ";
			}
			customerCondition += "id = " + customerId;
		}
		customerDto.setCustomerCondition(customerCondition.equals("")?null:customerCondition);

		return customerDto;
	}

	
	public String formatDate(Calendar calendar){
		int year = calendar.get(Calendar.YEAR);
		int month = calendar.get(Calendar.MONTH)+1;
		int date = calendar.get(Calendar.DAY_OF_MONTH);
		return year+"-"+month+"-"+date;
	}
}
